package com.suke.czx.modules.contact.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;
import com.suke.czx.common.utils.CodeConstant;
import com.suke.czx.common.utils.FieldConstant;
import com.suke.czx.common.utils.ParamValidateUtil;
import com.suke.czx.common.utils.R;
import com.suke.czx.common.validate.ContactSaveGroup;
import com.suke.czx.common.validate.ContactUpdateGroup;
import com.suke.czx.modules.contact.entity.Contact;
import com.suke.czx.modules.contact.service.ContactService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 应用模块名称: 联系人
 * 代码描述: 联系人控制层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2021/09/01 14:36:19
 */
@Validated
@RestController
@RequestMapping("/api/contact")
@AllArgsConstructor
@Api(value = "ContactController", tags = "联系人管理")
public class ContactController extends AbstractController {

    private final ContactService contactService;

    /**
     * 分页查询联系人列表
     * @param params 查询参数
     * @return VO
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:contact:list')")
    public R list(@RequestParam Map<String, Object> params) {
        if (StrUtil.isBlankIfStr(params.get(FieldConstant.PAGE)) || StrUtil.isBlankIfStr(FieldConstant.LIMIT)) {
            return R.error("缺少分页信息");
        }
        if (StrUtil.isBlankIfStr(params.get(FieldConstant.TYPE))) {
            return R.error("联系人类型不能为空");
        }
        if (StrUtil.isBlankIfStr(params.get(FieldConstant.RELATION_ID))) {
            return R.error("联系人关联编码不能为空");
        }
        // 查询列表数据
        QueryWrapper<Contact> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.DEL_FLG, CodeConstant.NOT_DEL).eq(FieldConstant.TYPE, params.get(FieldConstant.TYPE))
                .eq(StrUtil.toUnderlineCase(FieldConstant.RELATION_ID), params.get(FieldConstant.RELATION_ID));
        IPage<Contact> contactPage = contactService.page(mpPageConvert.pageParamConvert(params), queryWrapper);
        return Objects.requireNonNull(R.ok().put(FieldConstant.TOTAL, contactPage.getTotal())).setData(Optional.ofNullable(contactPage.getRecords()).orElse(Lists.newArrayList()));
    }

    /**
     * 获取联系人详情
     * @param contactId 联系人id
     * @return VO
     */
    @RequestMapping(value = "/info/{contactId}", method = RequestMethod.GET)
    @PreAuthorize("hasRole('but:contact:info')")
    public R info(@PathVariable("contactId") Long contactId) {
        Contact contact = contactService.getById(contactId);
        return R.ok().setData(contact);
    }

    /**
     * 保存联系人
     * @param contact 联系人
     * @param bindingResult bindingResult
     * @return VO
     */
    @SysLog("保存联系人")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:contact:save')")
    public R save(@Validated(ContactSaveGroup.class) Contact contact, BindingResult bindingResult) {
        // 入参校验结果
        if (bindingResult.hasErrors()) {
            return R.error(ParamValidateUtil.paramVilated(bindingResult));
        }
        contact.setCreator(getUserId());
        contact.setCreateTime(new Date());
        contactService.save(contact);
        return R.ok();
    }

    /**
     * 更新联系人
     * @param contact 联系人
     * @param bindingResult bindingResult
     * @return VO
     */
    @SysLog("更新联系人")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:contact:update')")
    public R update(@Validated(ContactUpdateGroup.class) Contact contact, BindingResult bindingResult) {
        // 入参校验结果
        if (bindingResult.hasErrors()) {
            return R.error(ParamValidateUtil.paramVilated(bindingResult));
        }
        contact.setUpdater(getUserId());
        contact.setUpdateTime(new Date());
        contactService.updateById(contact);
        return R.ok();
    }

    /**
     * 删除联系人
     * @param contactId 联系人编码
     * @return VO
     */
    @SysLog("删除联系人")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:contact:delete')")
    public R delete(@NotNull(message = "联系人编码不能为空") Long contactId) {
        return contactService.updateDelContact(contactId, getUserId());
    }

}
